<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .message {
            background-color: #f1f1f1;
            border: 1px solid #ccc;
            padding: 10px;
            margin-bottom: 10px;
        }

    </style>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">
    </script>
    <script>
        const token = uuid(10,16);
        console.log(token)
        let ws = new WebSocket('ws://localhost:8080/chat/' + token);
        ws.onopen = function() {
            console.log("Connected to the chat server");
            // ws.send("Hello, server!");
        };

        ws.onmessage = function(event) {
            console.log("Received from chat server: " , event.data);
            if(event.data.length>2) {
                let msg = JSON.parse(event.data)
                console.log(msg)
                $("#chat-box").prepend(`<div class="message">${msg.username} 说: ${msg.msg}</div>`)
            }
        };

        ws.onclose = function() {
            console.log("Disconnected from the server");
        };

        ws.onerror = function(event) {
            console.log("Error: " + event.data);
        };

        function send(){
            let message = {
                msg: document.getElementById("msg").value,
                username: document.getElementById("username").value, // 示例：添加用户名字段
                //timestamp: new Date().getTime() // 示例：添加时间戳字段
            };

            ws.send(JSON.stringify(message));
        }

        /**
         * 随机生成[len]长度的[radix]进制数
         * @param len
         * @param radix 默认62
         * @returns {string}
         */
        function uuid (len, radix) {
            const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
            const uuid = [];
            radix = radix || chars.length;

            for (let i = 0; i < len; i++) {
                uuid[i] = chars[0 | Math.random() * radix];
            }

            return uuid.join('');
        }
    </script>
</head>
<body>
<div>
    昵称:<input id="username"/><br/>
    输入信息:<input id="msg"/>
    <button onclick="send()">发送</button>
</div>
    <div id="chat-box">
        <!-- 聊天消息内容 -->
        <div class="message">消息内容1</div>
        <div class="message">消息内容2</div>
        <div class="message">消息内容3</div>
        <!-- 在这里继续添加更多的聊天消息 -->
    </div>

    <script>
        // document.getElementById("name").value=token
    </script>

</body>
</html>